<template>
  <a-modal
    :visible="visible"
    :title="category && category.id ? '编辑分类' : '新增分类'"
    @ok="handleSubmit"
    @cancel="$emit('update:visible', false)"
    @visible-change="handleVisibleChange"
  >
    <a-form :model="form" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
      <a-form-item field="name" label="分类名" :rules="[{ required: true, message: '请输入分类名' }]">
        <a-input v-model="form.name" placeholder="请输入分类名" />
      </a-form-item>
      <a-form-item field="sort" label="排序" :rules="[{ required: true, message: '请输入排序权重' }]">
        <a-input-number v-model="form.sort" placeholder="请输入排序权重" :min="0" />
      </a-form-item>
      <a-form-item field="visibility" label="是否展示">
        <a-radio-group v-model="form.visibility">
          <a-radio :value="true">展示</a-radio>
          <a-radio :value="false">隐藏</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { CategoryDetail } from '@/api/category'
import { Message } from '@arco-design/web-vue'

// 定义组件属性
const props = defineProps<{
  visible: boolean
  category: CategoryDetail | null
}>()

// 定义组件事件
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'submit', form: CategoryDetail): void
}>()

// 处理对话框可见性变化
const handleVisibleChange = (val: boolean) => {
  emit('update:visible', val)
}

// 表单数据
const form = ref<CategoryDetail>({
  id: 0,
  name: '',
  sort: 0,
  visibility: true,
})

// 监听category变化，更新表单数据
watch(
  () => props.category,
  (newVal) => {
    if (newVal) {
      form.value = { ...newVal }
    } else {
      // 重置表单为默认值
      form.value = {
        id: 0,
        name: '',
        sort: 0,
        visibility: true,
      }
    }
  },
  { immediate: true, deep: true }
)

// 提交表单
const handleSubmit = () => {
  if (!form.value.name) {
    Message.error('请输入分类名')
    return
  }
  if (form.value.sort === undefined || form.value.sort === null) {
    Message.error('请输入排序权重')
    return
  }
  emit('submit', form.value)
}
</script>

<style scoped lang="less">
// 组件特定样式可以在这里添加
</style>
